<template>
  <div>
    <div>
      <van-nav-bar
        title="登录"
        left-text="返回"
        left-arrow
        @click-left="$router.go(-1)"
      />
      <h1>手机号登录</h1>
      <p>未注册的手机号将自动注册</p>
    </div>

    <!-- 输入手机号，调起手机号键盘 -->
    <van-field
      v-model="tel"
      type="tel"
      label="手机号"
      placeholder="请输入手机号"
    />
    <!-- 输入密码
    <van-field
      v-model="password"
      type="password"
      label="密码"
      placeholder="请输入密码"
    /> -->
    <!-- 输入图片验证码 -->
    <van-field
      v-model="captcha"
      label="图片验证码"
      placeholder="请输入图片验证码"
    >
      <div slot="button">
        <img
          :src="'data:image/png;base64,' + captchaImg"
          alt="无效"
          @click="updateChptchaImg"
        />
      </div>
    </van-field>

    <!-- 允许输入正整数，调起纯数字键盘 -->
    <van-field
      v-model="checkMessage"
      center
      clearable
      label="短信验证码"
      placeholder="请输入短信验证码"
    >
      <template #button>
        <van-button size="small" type="primary" @click="getCode">{{
          totalSecond === second ? "发送验证码" : second + "秒后重新发送"
        }}</van-button>
      </template>
    </van-field>
    <van-button round type="info" size="large" @click="submit">登录</van-button>
  </div>
</template>

<script>
import { getCaptcha, getCode, login } from '@/api/login'
import { Toast } from 'vant'

export default {
  data () {
    return {
      // 电话号
      tel: '12345678901',
      // 密码
      // password: '',
      // 用户输入的图片验证码
      captcha: '',
      // 后端发来的短信验证码
      checkMessageKey: '',
      // 后端发来的图片验证码
      captchaImgKey: '',
      // 用户输入的短信验证码
      checkMessage: '246810',
      // 用来存储图片验证码的base64
      captchaImg: '',
      // 发送短信验证码后需等待的总秒数
      totalSecond: '60',
      // 还需等待秒数
      second: '60',
      // 当前开启的定时器
      timer: null
    }
  },
  methods: {
    updateChptchaImg () {
      this.loadingCaptchaImg()
    },
    verificationCaptcha () {
      return this.captcha === this.captchaImgKey
    },
    verificationCode () {
      return this.checkMessage === this.checkMessageKey
    },
    async getCode () {
      // 确保已输入正确的手机号和图片验证码
      if (this.tel.length === 11) {
        if (this.verificationCaptcha()) {
          if (!this.timer && this.second === this.totalSecond) {
            // 开启倒计时
            this.timer = setInterval(() => {
              this.second--
              if (this.second < 1) {
                this.second = this.totalSecond
                clearInterval(this.timer)
                this.timer = null
              }
            }, 1000)
            // 发送请求，获取验证码
            const res = await getCode()
            this.checkMessageKey = res.data
            console.log('checkMessageKey:', this.checkMessageKey)
            Toast('已发送验证码')
          }
        } else {
          Toast('请输入正确的图片验证码!')
        }
      } else {
        Toast('请输入正确的手机号!')
      }
    },
    async submit () {
      if (
        this.verificationCaptcha() &&
        this.verificationCode() &&
        this.tel.length === 11
      ) {
        const res = await login({
          tel: this.tel
        })
        console.log(res)
        if (res.status === 200) {
          this.$store.commit('user/setUserInfo', res.data)
          Toast('登录成功！')
          // 判断有无回跳地址
          const url = this.$route.query.backUrl || '/'
          this.$router.replace(url)
        } else if (res.status === 201) {
          Toast('注册成功·！')
        } else {
          Toast('登录失败！')
        }
      } else {
        Toast('手机或验证码有误')
      }
    },
    async loadingCaptchaImg () {
      const res = await getCaptcha()
      this.captchaImg = res.data.base64Str
      this.captchaImgKey = res.data.value
      // console.log('base64Str: ' + res.data.base64Str + ' captchaImg: ' + this.captchaImg)
      // console.log(res.data)
    }
  },
  created () {
    this.loadingCaptchaImg()
  }
}
</script>

<style>
</style>
